import utils from "./utils";
export default {
  onDrawn(drawnFn) {
    if (!drawnFn || typeof drawnFn != "function") drawnFn = function() {};
    this.drawnFn = drawnFn;
  },
  onMousedown(opt, canvas) {
    var drawObj = {
      id: new Date().getTime() + "_obj",
    };
    drawObj.isDrawing = true;
    drawObj.drawType = "Circle";
    drawObj.pointers = [
      {
        y: opt.absolutePointer.y,
        x: opt.absolutePointer.x,
      },
      {
        y: opt.absolutePointer.y,
        x: opt.absolutePointer.x,
      },
    ];
    this.drawObj = drawObj;
  },
  onMousemove(opt, canvas) {
    if (!this.drawObj.isDrawing) return;

    this.drawObj.pointers[1].x = opt.absolutePointer.x;
    this.drawObj.pointers[1].y = opt.absolutePointer.y;
    this.draw(canvas, this.drawObj);
  },
  onMouseup(opt, canvas) {
    this.drawObj.isDrawing = false;
    if (this.drawnFn) this.drawnFn(this.drawObj);
  },
  draw(canvas, drawObj) {
    let width = drawObj.pointers[1].x - drawObj.pointers[0].x;
    let height = drawObj.pointers[1].y - drawObj.pointers[0].y;

    let radius = Math.sqrt(width * width + height * height) / 2;

    let top = drawObj.pointers[0].y + height / 2 - radius;
    let left = drawObj.pointers[0].x + width / 2 - radius;
    var drawOptions ={}
    if (drawObj.fabricObj) {
      drawOptions = {
        top: top,
        left: left,
        radius: radius,
        strokeWidth: 3 / canvas.getZoom(),
      }
      drawObj.fabricObj.set(utils.combineOptions(drawOptions,drawObj.drawOptions));
      canvas.requestRenderAll();
    } else {
      drawOptions = {
        top: top,
        left: left,
        radius: radius,
        fill: "rgb(0,0,0,0)",
        strokeWidth: 3 / canvas.getZoom(),
        stroke: "rgba(100,200,200,0.8)",
        selectable: false,
      }
      drawObj.fabricObj = new fabric.Circle(utils.combineOptions(drawOptions,drawObj.drawOptions));
      canvas.add(drawObj.fabricObj);
    }
    drawOptions=null;
  },
  remove(canvas, drawObj) {
    if (drawObj.fabricObj) canvas.remove(drawObj.fabricObj);
  },
};
